<script setup>
import {ref} from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
let router = useRouter();
//登录
const form = ref({})
const onSubmit = () => {
  axios.post('api/auth/login',form.value).then(
      res=>{
        console.log(res.data.data)
        if(res.data.code === 200){
          ElMessage.success("登陆成功")
          let token = res.data.data.token;
          localStorage.setItem("token",token);
          axios.defaults.headers.common.token = token
          //跳转页面
          router.push(
              {
                path: "/coupon",
                params:{
                  roleId:res.data.data.roleId,
                  username:res.data.data.username
                }
              }
          )
        }else {
          ElMessage.error(res.data.msg)
        }
      }
  )
}
//注册
const registerField = ref({})
const dialogFormVisible = ref(false)
const registerFormRef = ref()

// 手机号正则验证规则
const phoneRegex = /^1[3-9]\d{9}$/

// 表单验证规则
const registerRules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入手机号'))
        } else if (!phoneRegex.test(value)) {
          callback(new Error('请输入正确的手机号格式'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度在 4 到 6 个字符', trigger: 'blur' }
  ]
})

const register = () => {
  dialogFormVisible.value = true
}

//获取验证码
const sendCode = () => {
  // 验证手机号格式
  if (!registerField.value.phone) {
    ElMessage.error('请先输入手机号')
    return
  }
  if (!phoneRegex.test(registerField.value.phone)) {
    ElMessage.error('请输入正确的手机号格式')
    return
  }
  
  let phone = registerField.value.phone;
  axios.get('api/auth/sendCode/'+phone).then(
      res=>{
        if(res.data.code === 200){
          ElMessage.success("发送成功")
        }else {
          ElMessage.error(res.data.msg)
        }
      }
  )
}

//注册
const registerNewUser = () => {
  registerFormRef.value.validate((valid) => {
    if (valid) {
      axios.post('api/auth/register',registerField.value).then(
          res=>{
            if(res.data.code === 200){
              ElMessage.success("注册成功,请重新登录")
              //清空数据
              registerField.value = {}
              //关闭弹框
              dialogFormVisible.value = false
            }else {
              ElMessage.error(res.data.msg)
            }
          }
      )
    } else {
      ElMessage.error('请检查表单填写')
      return false
    }
  })
}
</script>

<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="手机号">
      <el-input v-model="form.phone" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="form.password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">登录</el-button>
      <el-button @click="register">注册</el-button>
    </el-form-item>
  </el-form>



<!--  注册弹框-->
  <el-dialog v-model="dialogFormVisible" title="用户注册" width="500">
    <el-form :model="registerField" :rules="registerRules" ref="registerFormRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerField.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerField.password" type="password" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="registerField.phone" />
      </el-form-item>
      <el-row>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="registerField.code" />
        </el-form-item>
        <el-button  @click="sendCode">发送验证码</el-button>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false;registerField.value = {}">取消</el-button>
        <el-button type="primary" @click="registerNewUser">
          注册
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>

</style>
